<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useBlogStore } from '@/store/blog'
import { useAuthStore } from '@/store/auth'

const router = useRouter()
const blogStore = useBlogStore()
const authStore = useAuthStore()

const userBlogs = ref([])
const loading = ref(true)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalBlogs = ref(0)
const sortBy = ref('createTime')
const sortDirection = ref('desc')
const selectedStatus = ref('all')

// 计算属性：过滤后的博客列表
const filteredBlogs = computed(() => {
  let filtered = [...userBlogs.value]
  
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(blog => 
      blog.title.toLowerCase().includes(query) || 
      (blog.content ? blog.content.replace(/<[^>]+>/g, '').toLowerCase().includes(query) : false)
    )
  }
  
  if (selectedStatus.value !== 'all') {
    filtered = filtered.filter(blog => blog.status === selectedStatus.value)
  }
  
  // 排序
  filtered.sort((a, b) => {
    const modifier = sortDirection.value === 'asc' ? 1 : -1
    if (sortBy.value === 'createTime') {
      return modifier * (new Date(a.createTime) - new Date(b.createTime))
    } else if (sortBy.value === 'views') {
      return modifier * ((a.views || 0) - (b.views || 0))
    } else if (sortBy.value === 'likes') {
      return modifier * ((a.likeCount || 0) - (b.likeCount || 0))
    }
    return 0
  })
  
  return filtered
})

// 计算属性：分页后的博客列表
const paginatedBlogs = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredBlogs.value.slice(start, end)
})

// 计算属性：总页数
const totalPages = computed(() => {
  return Math.ceil(filteredBlogs.value.length / pageSize.value)
})

onMounted(async () => {
  if (!authStore.isAuthenticated) {
    router.push('/login')
    return
  }
  
  fetchUserBlogs()
})

const fetchUserBlogs = async () => {
  try {
    loading.value = true
    const response = await blogStore.fetchUserBlogs(authStore.user.id)
    userBlogs.value = response.content || []
    totalBlogs.value = userBlogs.value.length
  } catch (error) {
    console.error('Failed to load user blogs:', error)
  } finally {
    loading.value = false
  }
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const navigateToEditBlog = (blogId) => {
  router.push(`/user/edit-blog/${blogId}`)
}

const navigateToCreateBlog = () => {
  router.push('/user/create-blog')
}

const navigateToBlog = (blogId) => {
  router.push(`/blogs/${blogId}`)
}

const deleteBlog = async (blogId) => {
  if (!confirm('确定要删除这篇博客吗？此操作不可恢复。')) {
    return
  }
  
  try {
    await blogStore.deleteBlog(blogId)
    userBlogs.value = userBlogs.value.filter(blog => blog.id !== blogId)
    totalBlogs.value = userBlogs.value.length
  } catch (error) {
    console.error('Failed to delete blog:', error)
  }
}

const changePage = (page) => {
  currentPage.value = page
}

const changeSort = (field) => {
  if (sortBy.value === field) {
    sortDirection.value = sortDirection.value === 'asc' ? 'desc' : 'asc'
  } else {
    sortBy.value = field
    sortDirection.value = 'desc'
  }
}

const getBlogStatusText = (status) => {
  const statusMap = {
    'draft': '草稿',
    'published': '已发布',
    'archived': '已归档'
  }
  return statusMap[status] || status
}

const getBlogStatusClass = (status) => {
  return {
    'status-draft': status === 'draft',
    'status-published': status === 'published',
    'status-archived': status === 'archived'
  }
}
</script>

<template>
  <div class="my-blogs">
    <div class="page-header">
      <h2 class="page-title">我的博客</h2>
      <button class="btn btn-primary" @click="navigateToCreateBlog">
        <span class="icon">✏️</span> 创建新博客
      </button>
    </div>
    
    <div class="filter-section card">
      <div class="search-container">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索博客标题或内容..." 
          class="search-input"
        />
        <span class="search-icon">🔍</span>
      </div>
      
      <div class="filters">
        <div class="filter">
          <label for="status">状态：</label>
          <select id="status" v-model="selectedStatus" class="filter-select">
            <option value="all">全部</option>
            <option value="published">已发布</option>
            <option value="draft">草稿</option>
            <option value="archived">已归档</option>
          </select>
        </div>
        
        <div class="filter">
          <label for="sort">排序：</label>
          <select id="sort" v-model="sortBy" class="filter-select">
            <option value="createTime">创建时间</option>
            <option value="views">浏览量</option>
            <option value="likes">点赞数</option>
          </select>
        </div>
        
        <div class="filter">
          <button 
            class="btn btn-secondary btn-sort" 
            @click="sortDirection = sortDirection === 'asc' ? 'desc' : 'asc'"
          >
            {{ sortDirection === 'asc' ? '↑' : '↓' }}
          </button>
        </div>
      </div>
    </div>
    
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
    </div>
    
    <div v-else-if="userBlogs.length === 0" class="empty-blogs card">
      <div class="empty-icon">📝</div>
      <h3>您还没有发布任何博客</h3>
      <p>点击上方的"创建新博客"按钮，开始您的创作之旅吧！</p>
    </div>
    
    <template v-else>
      <div class="blogs-stats">
        共 <strong>{{ filteredBlogs.length }}</strong> 篇博客
      </div>
      
      <div class="blogs-table-wrapper card">
        <table class="blogs-table">
          <thead>
            <tr>
              <th @click="changeSort('title')">标题</th>
              <th class="status-col">状态</th>
              <th @click="changeSort('createTime')" class="date-col">
                创建时间
                <span v-if="sortBy === 'createTime'" class="sort-indicator">
                  {{ sortDirection === 'asc' ? '↑' : '↓' }}
                </span>
              </th>
              <th @click="changeSort('views')" class="views-col">
                浏览量
                <span v-if="sortBy === 'views'" class="sort-indicator">
                  {{ sortDirection === 'asc' ? '↑' : '↓' }}
                </span>
              </th>
              <th @click="changeSort('likes')" class="likes-col">
                点赞数
                <span v-if="sortBy === 'likes'" class="sort-indicator">
                  {{ sortDirection === 'asc' ? '↑' : '↓' }}
                </span>
              </th>
              <th class="actions-col">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="blog in paginatedBlogs" :key="blog.id" class="blog-row">
              <td class="title-col" @click="navigateToBlog(blog.id)">
                {{ blog.title }}
              </td>
              <td class="status-col">
                <span :class="['blog-status', getBlogStatusClass(blog.status)]">
                  {{ getBlogStatusText(blog.status) }}
                </span>
              </td>
              <td class="date-col">{{ formatDate(blog.createTime) }}</td>
              <td class="views-col">{{ blog.views || 0 }}</td>
              <td class="likes-col">{{ blog.likeCount || blog.likes || 0 }}</td>
              <td class="actions-col">
                <button 
                  class="action-btn view-btn" 
                  title="查看" 
                  @click="navigateToBlog(blog.id)"
                >👁️</button>
                <button 
                  class="action-btn edit-btn" 
                  title="编辑" 
                  @click="navigateToEditBlog(blog.id)"
                >✏️</button>
                <button 
                  class="action-btn delete-btn" 
                  title="删除" 
                  @click="deleteBlog(blog.id)"
                >🗑️</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- 分页 -->
      <div v-if="totalPages > 1" class="pagination">
        <button 
          class="pagination-btn prev" 
          :disabled="currentPage === 1"
          @click="changePage(currentPage - 1)"
        >
          &laquo; 上一页
        </button>
        
        <div class="pagination-pages">
          <button 
            v-for="page in totalPages" 
            :key="page" 
            class="pagination-btn page" 
            :class="{ active: currentPage === page }"
            @click="changePage(page)"
          >
            {{ page }}
          </button>
        </div>
        
        <button 
          class="pagination-btn next" 
          :disabled="currentPage === totalPages"
          @click="changePage(currentPage + 1)"
        >
          下一页 &raquo;
        </button>
      </div>
    </template>
  </div>
</template>

<style>
.my-blogs {
  padding: 0.5rem 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.page-title {
  font-size: 1.75rem;
  font-weight: 600;
  margin: 0;
}

.filter-section {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  margin-bottom: 1.5rem;
  gap: 1rem;
}

.search-container {
  position: relative;
  flex: 1;
  min-width: 250px;
}

.search-input {
  width: 100%;
  padding: 0.625rem 1rem 0.625rem 2.5rem;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  font-size: 0.9rem;
}

.search-icon {
  position: absolute;
  left: 0.75rem;
  top: 50%;
  transform: translateY(-50%);
  color: var(--text-light);
}

.filters {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.filter {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.filter label {
  font-weight: 500;
  color: var(--text-light);
}

.filter-select {
  padding: 0.5rem;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  background-color: white;
}

.btn-sort {
  padding: 0.5rem 0.75rem;
  min-width: 40px;
}

.blogs-stats {
  margin-bottom: 1rem;
  color: var(--text-light);
}

.empty-blogs {
  padding: 3rem 1rem;
  text-align: center;
}

.empty-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.blogs-table-wrapper {
  overflow-x: auto;
  margin-bottom: 1.5rem;
}

.blogs-table {
  width: 100%;
  border-collapse: collapse;
}

.blogs-table th {
  background-color: #f8f9fa;
  padding: 0.75rem 1rem;
  text-align: left;
  font-weight: 600;
  color: var(--text-light);
  border-bottom: 1px solid var(--border-color);
  cursor: pointer;
  transition: background-color 0.2s;
  white-space: nowrap;
}

.blogs-table th:hover {
  background-color: #f0f2f5;
}

.blogs-table td {
  padding: 0.75rem 1rem;
  border-bottom: 1px solid var(--border-color);
}

.blog-row:hover {
  background-color: #f8f9fa;
}

.title-col {
  max-width: 300px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
  color: var(--primary-color);
}

.title-col:hover {
  text-decoration: underline;
}

.status-col {
  width: 90px;
}

.date-col {
  width: 180px;
  white-space: nowrap;
}

.views-col, .likes-col {
  width: 100px;
  text-align: center;
}

.actions-col {
  width: 120px;
  white-space: nowrap;
  text-align: center;
}

.blog-status {
  display: inline-block;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: 500;
}

.status-draft {
  background-color: #fdf6ec;
  color: #faad14;
}

.status-published {
  background-color: #f6ffed;
  color: #52c41a;
}

.status-archived {
  background-color: #f5f5f5;
  color: #8c8c8c;
}

.action-btn {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 1.1rem;
  padding: 0.25rem;
  margin: 0 0.25rem;
  transition: transform 0.2s;
}

.action-btn:hover {
  transform: scale(1.2);
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 1.5rem;
  gap: 0.5rem;
}

.pagination-btn {
  padding: 0.5rem 0.75rem;
  border: 1px solid var(--border-color);
  background-color: white;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.pagination-btn:hover:not(:disabled) {
  background-color: #f0f2f5;
  border-color: var(--primary-color);
}

.pagination-btn.active {
  background-color: var(--primary-color);
  color: white;
  border-color: var(--primary-color);
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination-pages {
  display: flex;
  gap: 0.25rem;
}

@media (max-width: 768px) {
  .filter-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filters {
    flex-wrap: wrap;
  }
  
  .date-col, .status-col {
    display: none;
  }
  
  .actions-col {
    width: 100px;
  }
}
</style> 